const db = require('../database/order')
const { normalizeOrder } = require('../classes/order')

module.exports = {
  orderList: async (user) => {
    const dbResult = await db.orderListDB(user)
    return normalizeOrder(dbResult)
  },
  orderCreate: async (order) => {
    const dbResult = await db.orderCreateDB(order)
    return dbResult.affectedRows 
      ? Promise.resolve({
          id: dbResult.insertId
        })
      : Promise.reject('下单失败')
  },
  orderDetail: async (id, user) => {
    const dbResult = await db.orderDetailDB(id, user)
    return dbResult.length 
      ? normalizeOrder(dbResult[0])
      : Promise.reject('查询不到订单信息')
  },
  orderDelete: async (id, user) => {
    const dbResult = await db.orderDeleteDB(id, user)
    return dbResult.changedRows 
      ? Promise.resolve('删除成功')
      : Promise.reject('删除失败')
  },
  orderUpdateState: async (orderId, user, state) => {
    const dbResult = await db.orderUpdateState(orderId, user, state)
    return dbResult.changedRows 
      ? Promise.resolve('操作成功')
      : Promise.reject('操作失败')
  }
}